import getSqliteClient from "@/services/sqlite/init";
import {
    ChatMessageBatchDelete,
    ChatMessageCreate,
    ChatMessageDelete,
    ChatMessageQuery,
    ChatMessage,
    ChatMessageUpdate, MessageStatus,
} from "@/types/chat-message";

const client = getSqliteClient();

/**
 * 基于游标的分页查询
 * @param sessionId 会话ID
 * @param ownerId 所有者ID
 * @param lastTime 上次查询的时间戳
 * @param pageSize 每页大小
 * @returns {Promise<ChatMessage<any,any>[]>} 分页结果
 */
export async function queryChatMessagesByCursor({
                                                    sessionId,
                                                    ownerId,
                                                    lastTime,
                                                    pageSize = 20,
                                                }: ChatMessageQuery): Promise<ChatMessage<any, any>[]> {
    let query = `
    SELECT chat_message.*, chat_user.name AS user_name, chat_user.avatar AS user_avatar FROM chat_message
    LEFT JOIN chat_user ON chat_message.user_id = chat_user.id
    WHERE chat_message.session_id = ? AND chat_message.owner_id = ?`;
    const params: any[] = [sessionId, ownerId];
    if (lastTime) {
        query += ` AND create_time < ?`;
        params.push(lastTime);
        query += ` ORDER BY create_time ASC LIMIT ?`;
    } else {
        query += ` ORDER BY create_time DESC LIMIT ?`;
    }
    params.push(pageSize);
    const rows = await client.getAllAsync(query, params);
    return rows.map(mapToChatMessage);
}

/**
 * 删除指定会话下的所有聊天消息
 * @param sessionId 会话ID
 * @param ownerId 所有者ID
 * @returns {Promise<void>}
 */
export async function deleteAllMessagesBySessionId({
                                                       sessionId,
                                                       ownerId,
                                                   }: ChatMessageBatchDelete): Promise<void> {
    const query = `DELETE FROM chat_message WHERE session_id = ? AND owner_id = ?;`;
    await client.runAsync(query, [sessionId, ownerId]);
}

/**
 * 批量删除聊天消息
 * @param messageIds 消息ID数组
 * @param ownerId 所有者ID
 * @returns {Promise<void>}
 */
export async function deleteBatchMessagesByIds(messageIds: string[], ownerId: string): Promise<void> {
    const placeholders = messageIds.map(() => "?").join(", ");
    const query = `DELETE FROM chat_message WHERE message_id IN (${placeholders}) AND owner_id = ?;`;
    await client.runAsync(query, [...messageIds, ownerId]);
}

/**
 * 插入聊天消息
 * @param message ChatMessage<any,any>
 * @returns {Promise<void>}
 */
export async function insertChatMessage(
    message: ChatMessageCreate<any, any>
): Promise<void> {
    const update = `
            INSERT INTO chat_message (
                message_id, owner_id, user_id,session_id, message_type, content, system, status, revoke_status,
                reply_id, reply_user_name, reply_content, reply_message_type, reply_revoke_status, create_time
            ) VALUES (?, ? , ? , ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
        `;
    await client
        .runAsync(update, [
            message.messageId,
            message.ownerId,
            message.user.id,
            message.sessionId,
            message.messageType,
            JSON.stringify(message.content),
            message.system || false, // 默认非系统消息
            message.status || MessageStatus.SENDING, // 默认状态为发送中
            message.revokeStatus || false, // 默认未撤回
            message.reply?.replyMessageId || null,
            message.reply?.replyUserName || null,
            JSON.stringify(message.reply?.replyContent || null),
            message.reply?.replyMessageType || null,
            message.reply?.replyRevokeStatus || false,
            message.createTime,
        ])
        .catch((e) => {
            console.error(e);
        });
}

/**
 * 更新聊天消息
 * @param messageId 消息ID
 * @param ownerId 所有者ID
 * @param status 消息状态
 * @param content 消息内容
 * @param revokeStatus 撤回状态
 * @returns {Promise<void>}
 */
export async function updateChatMessage({
                                            messageId,
                                            ownerId,
                                            status,
                                            content,
                                            revokeStatus,
                                        }: ChatMessageUpdate): Promise<void> {
    const fields: string[] = [];
    const params: any[] = [];

    if (status !== undefined) {
        fields.push("status = ?");
        params.push(status);
    }

    if (revokeStatus !== undefined) {
        fields.push("revoke_status = ?");
        params.push(revokeStatus);
    }

    if (content !== undefined) {
        fields.push("content = ?");
        params.push(JSON.stringify(content));
    }

    if (fields.length === 0) return;

    const query = `UPDATE chat_message SET ${fields.join(
    ", "
  )} WHERE message_id = ? AND owner_id = ?;`;
    params.push(messageId, ownerId);
    await client.runAsync(query, params).then(r => {
        console.log(r)
    })
        .catch((e) => {
            console.error(e);
        });
}

/**
 * 删除聊天消息
 * @param messageId 消息ID
 * @param ownerId
 * @returns {Promise<void>}
 */
export async function deleteChatMessage({
                                            messageId,
                                            ownerId,
                                        }: ChatMessageDelete): Promise<void> {
    const query = `DELETE FROM chat_message WHERE message_id = ? AND user_id = ?;`;
    await client.runAsync(query, [messageId, ownerId]);
}

/**
 * 清空当前用户的所有聊天消息
 * @returns {Promise<void>}
 */
export async function clearAllMessages(ownerId: string): Promise<void> {
    const query = `DELETE FROM chat_message WHERE ownerId = ?;`;
    await client.runAsync(query, [ownerId]);
}

function mapToChatMessage(row: any): ChatMessage<any, any> {
    let chatMessage: ChatMessage<any, any> = {
        messageId: row.message_id,
        sessionId: row.session_id,
        messageType: row.message_type,
        user: {
            id: row.user_id,
            name: row.user_name,
            avatar: row.user_avatar,
            updateTime: row.update_time,
        },
        status: row.status,
        content: JSON.parse(row.content),
        system: row.system,
        revokeStatus: row.revoke_status,
        createTime: row.create_time,
    };
    if (row.reply_id) {
        chatMessage = {
            ...chatMessage,
            reply: {
                replyMessageId: row.reply_id,
                replyContent: JSON.parse(row.reply_content),
                replyMessageType: row.reply_message_type,
                replyUserName: row.reply_user_name,
                replyRevokeStatus: row.reply_revoke_status,
            },
        };
    }
    return chatMessage;
}
